package com.example.myapplication.camera.method;

import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CaptureRequest;
import android.media.MediaRecorder;
import android.os.Handler;
import android.util.Log;
import android.util.Size;
import android.view.Surface;
import android.view.SurfaceView;

import androidx.annotation.NonNull;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Create By TreeRoot
 * Create Time: 2024/08/12 02:00
 * Class Name: VideoRecordUtils
 * Description:
 *
 * @author TreeRoot
 */
public class VideoRecordUtils {
    public static Size WH_720X480 = new Size(960, 720);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.CHINA);
    private MediaRecorder mediaRecorder;
    private SurfaceView surfaceView;
    private CameraDevice mCameraDevice;
    List<Surface> surfaces = new ArrayList<>();
    private CaptureRequest.Builder mPreviewBuilder;
    private CameraCaptureSession mCameraCaptureSession;
    private Size size;

    /**
     * 初始化MediaRecorder，接受Camera有关参数
     */
    public void create(SurfaceView surfaceView, CameraDevice cameraDevice, Size size) {
        this.surfaceView = surfaceView;
        this.size = size;
        mCameraDevice = cameraDevice;
        try {
            //创建录制请求
            mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }




    /**
     * 停止录制
     */
    public void stopRecord() {
        if (mediaRecorder != null) {
            mediaRecorder.setOnErrorListener(null);
            mediaRecorder.setOnInfoListener(null);
            mediaRecorder.setPreviewDisplay(null);
            mediaRecorder.stop();
            mediaRecorder.reset();
        }
//        mediaRecorder.release();
//        mediaRecorder =null;
        surfaces.clear();
    }

    /**
     * 启动视频记录器
     */
    private void setupMediaRecorder() {
        mediaRecorder = new MediaRecorder();
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mediaRecorder.setOutputFile("/sdcard/proton/video/" + sdf.format(new Date()) + "_output.mp4");
        mediaRecorder.setVideoSize(size.getWidth(), size.getHeight());
        mediaRecorder.setVideoFrameRate(120);
        mediaRecorder.setVideoEncodingBitRate(2000 * 1024);
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        mediaRecorder.setOrientationHint(90);
        try {
            mediaRecorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void startRecord(Handler handler) {
        setupMediaRecorder();
        Surface previewSurface = surfaceView.getHolder().getSurface();
        surfaces.add(previewSurface);
        mPreviewBuilder.addTarget(previewSurface);
        Surface recordSurface = mediaRecorder.getSurface();
        surfaces.add(recordSurface);
        mPreviewBuilder.addTarget(recordSurface);
        mediaRecorder.start();
        try {
            // 创建会话 session
            mCameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(@NonNull CameraCaptureSession session) {
                    // 录像时同时开启预览，使得一直有画面
                    mCameraCaptureSession = session;
                    try {
                        mCameraCaptureSession.setRepeatingRequest(mPreviewBuilder.build(), new CameraCaptureSession.CaptureCallback() {
                            @Override
                            public void onCaptureStarted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, long timestamp, long frameNumber) {
                                super.onCaptureStarted(session, request, timestamp, frameNumber);
                                Log.i("TAG", "onCaptureStarted: "+timestamp);
                            }
                        }, handler);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                }
                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                }
            }, handler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
}
